<template>
  <div id="store">
    <div>
      <el-dialog :title="dialog1.title" :visible.sync="dialog1.visible">
        <el-form
          :model="store"
          :rules="rules"
          ref="store"
          label-width="100px"
          class="demo-ruleForm"
        >
          <div class="formItem">
            <input type="hidden" value="store.id" />
            <el-form-item style="flex: 1;" label="所属公司" prop="companyId">
              <el-select v-model="store.companyId" placeholder="请选择公司">
                <el-option
                  v-for="company in companys"
                  :key="company.id"
                  :label="company.name"
                  :value="company.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="flex: 1;" label="门店名称" prop="name">
              <el-input v-model="store.name"></el-input>
            </el-form-item>
          </div>
          <div class="formItem">
            <el-form-item style="flex: 1;" label="门店电话" prop="tel">
              <el-input v-model="store.tel"></el-input>
            </el-form-item>
            <el-form-item style="flex: 1;" label="门店联系人" prop="contactPerson">
              <el-input v-model="store.contactPerson"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="门店地址" prop="address">
            <el-input
              prefix-icon="el-icon-location"
              v-model="store.address"
              @focus="dialog2.visible = true"
            ></el-input>
          </el-form-item>
          <el-form-item label="门店备注" prop="remark">
            <el-input type="textarea" :rows="3" v-model="store.remark"></el-input>
          </el-form-item>
          <el-form-item label="门店图片" prop="picUrl">
            <singleImgUpload :url.sync="store.picUrl" dir="store"></singleImgUpload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('store')">确定</el-button>
            <el-button @click="resetForm('store')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div>
      <el-dialog :title="dialog2.title" :visible.sync="dialog2.visible">
        <el-card class="box-card">
          <div id="bmap">
            <div>
              <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="门店地址:" size="medium">
                  <el-input placeholder="门店地址" v-model="store.address"></el-input>
                </el-form-item>
                <el-form-item label="经度:">
                  <span style="color: gray;">{{ store.pointX }}</span>
                </el-form-item>
                <el-form-item label="维度:">
                  <span style="color: gray;">{{ store.pointY }}</span>
                </el-form-item>
                <el-form-item>
                  <el-button
                    size="medium"
                    type="primary"
                    icon="el-icon-search"
                    @click="searchAddress"
                  >查询</el-button>
                </el-form-item>
              </el-form>
            </div>
            <baidu-map
              :style="{ width: map.width, height: map.height }"
              ak="sGxmCuqwBomiLn9IapTY87xtMD1BpAsZ"
              :zoom="map.zoom"
              class="map"
              :center="{ lng: map.center.lng, lat: map.center.lat }"
              @ready="handler"
              :scroll-wheel-zoom="true"
            >
              <!--比例尺控件-->
              <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
              <!--缩放控件-->
              <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
            </baidu-map>
          </div>
        </el-card>
      </el-dialog>
    </div>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card">
          <div class="boxcard-head">
            <el-form :model="queryParam" ref="queryParam" inline class="demo-form-inline">
              <el-form-item label="门店名称:" prop="name">
                <el-input placeholder="门店名称" v-model="queryParam.name"></el-input>
              </el-form-item>
              <el-form-item label="门店联系人:" prop="contactPerson">
                <el-input placeholder="门店联系人" v-model="queryParam.contactPerson"></el-input>
              </el-form-item>
              <el-form-item label="门店电话:" prop="tel">
                <el-input placeholder="门店电话" v-model="queryParam.tel"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchStore">查询</el-button>
                <el-button @click="resetForm('queryParam')">重置</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="addStore">添加</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="boxcard-body">
            <el-table
              :data="list"
              style="width: 100%;"
              row-key="id"
              :header-cell-style="{ 'background-color': '#EEEEEE' }"
            >
              <el-table-column prop="name" label="门店名称"></el-table-column>
              <el-table-column prop="address" label="门店地址"></el-table-column>
              <el-table-column prop="tel" label="门店电话"></el-table-column>
              <el-table-column prop="contactPerson" label="门店联系人"></el-table-column>
              <el-table-column prop="remark" label="门店备注"></el-table-column>
              <el-table-column label="门店图片">
                <template slot-scope="scope">
                  <el-image v-if="scope.row.picUrl" style="width:70px;height:70px" :preview-src-list="[scope.row.picUrl]" :src="scope.row.picUrl" />
                </template>
              </el-table-column>
              <el-table-column prop="recommendNum" label="总会员数"></el-table-column>
              <el-table-column label="操作" width="240">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="updateStore(scope.row)">修改</el-button>
                  <el-button type="text" size="small" @click="deleteStore(scope.row)">删除</el-button>
                  <el-button type="text" size="small" @click="miniCode(scope.row)">小程序码</el-button>
                  <el-button type="text" size="small" @click="recommenderDialog(scope.row)">会员列表</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="page.pageSizes"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <a :href="miniCodeUrl" id="miniCodeUrl_store" target="_blank" style="display:none;"></a>
    <recommender v-bind:visible.sync="recommenderVisable" ref="recommender"></recommender>
  </div>
</template>

<script>
//百度地图
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
import BmScale from "vue-baidu-map/components/controls/Scale";
import BmNavigation from "vue-baidu-map/components/controls/Navigation";
import BmMarkerClusterer from "vue-baidu-map/components/extra/MarkerClusterer";
import BmMarker from "vue-baidu-map/components/overlays/Marker";
import BmInfoWindow from "vue-baidu-map/components/overlays/InfoWindow";
import { get, postJson, postXform } from "@/utils/request.js";
import singleImgUpload from "../../components/upload/SingleImgUpload.vue";
import recommender from "@/views/market/recommender";
export default {
  components: {
    BaiduMap,
    BmScale,
    BmNavigation,
    BmMarkerClusterer,
    BmMarker,
    BmInfoWindow,
    singleImgUpload,
    recommender
  },
  data() {
    return {
      store: {
        id: "",
        companyId: "",
        name: "",
        address: "",
        tel: "",
        contactPerson: "",
        remark: "",
        picUrl: "",
        pointX: "",
        pointY: ""
      },
      rules: {},
      dialog1: {
        title: "添加门店",
        visible: false
      },
      dialog2: {
        title: "确认地址",
        visible: false
      },
      map: {
        center: { lng: 118, lat: 32 },
        zoom: 14,
        width: "500px",
        height: "500px"
      },
      bmap: null,
      list: [],
      companys: [],
      page: {
        pageSize: 10,
        total: 0,
        currentPage: 1,
        pageSizes: [10, 20, 50]
      },
      queryParam: { name: "", contactPerson: "", tel:null},
      miniCodeUrl: "",
      recommenderVisable: false,
    };
  },
  created() {
    this.getList();
    get("/store/allCompany", {}).then(res => {
      this.companys = res.data.data;
    });
  },
  watch: {
    // 'dialog1.visible': {
    // 	handler() {
    // 		if (!this.dialog1.visible) {
    // 			this.store.picUrl = '';
    // 		}
    // 	},
    // 	immediate: true
    // }
  },
  methods: {
    setUrl(url) {
      this.store.picUrl = url;
    },
    addStore() {
      this.store = {
        id: "",
        companyId: "",
        name: "",
        address: "",
        tel: "",
        contactPerson: "",
        remark: "",
        picUrl: "",
        pointX: "",
        pointY: ""
      };
      this.dialog1 = { title: "添加门店", visible: true };
    },
    async searchStore() {
      this.getList();
    },
    updateStore(row) {
      this.store = {
        id: row.id,
        companyId: row.companyId,
        name: row.name,
        address: row.address,
        tel: row.tel,
        contactPerson: row.contactPerson,
        remark: row.remark,
        picUrl: row.picUrl,
        pointX: row.pointX,
        pointY: row.pointY
      };
      this.dialog1 = { title: "修改门店", visible: true };
    },
    deleteStore(row) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          postXform("/store/deleteStore", { id: row.id }).then(res => {
            this.$message({ message: "删除成功", type: "success" });
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getList();
    },
    async getList() {
      await get("/store/pageStore", {
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
        name:this.queryParam.name,
        contactPerson:this.queryParam.contactPerson,
        tel:this.queryParam.tel
      }).then(res => {
        this.list = res.data.data.list;
        this.page.total = Number.parseInt(res.data.data.total);
        this.page.currentPage = res.data.data.pageNum;
      });
    },
    submitForm(form) {
      this.$refs.store.validate(valid => {
        if (valid) {
          let param = { ...this.store };
          if (this.store.id === "") {
            postXform("/store/addStore", param).then(res => {
              this.dialog1.visible = false;
              this.$message({ message: "添加成功", type: "success" });
              this.getList();
            });
          } else {
            postXform("/store/updateStore", param).then(res => {
              this.dialog1.visible = false;
              this.$message({ message: "修改成功", type: "success" });
              this.getList();
            });
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      if (formName == "queryParam") {
        this.getList();
      }
      // this.store = {
      //   id: "",
      //   companyId: "",
      //   name: "",
      //   address: "",
      //   tel: "",
      //   contactPerson: "",
      //   remark: "",
      //   picUrl: "",
      //   pointX: "",
      //   pointY: ""
      // };
    },
    searchAddress() {
      let this_ = this;
      this_.bmap.clearOverlays();
      var localSearch = new BMap.LocalSearch(this_.bmap);
      localSearch.enableAutoViewport();
      var keyword = this.store.address;
      localSearch.setSearchCompleteCallback(function(result) {
        if (result != null) {
          var poi = result.getPoi(0);
          this_.bmap.centerAndZoom(poi.point, 14);
          var marker = new BMap.Marker(
            new BMap.Point(poi.point.lng, poi.point.lat)
          );
          this_.bmap.addOverlay(marker);
          marker.setAnimation(BMAP_ANIMATION_BOUNCE);
          this_.store.pointX = poi.point.lng;
          this_.store.pointY = poi.point.lat;
        }
      });
      localSearch.search(keyword);
    },
    //地图初始化
    handler({ BMap, map }) {
      let this_ = this;
      this.map.width = document.getElementById("bmap").clientWidth + "px";
      this.map.height = document.body.clientHeight / 2 + "px";
      this.bmap = map;
      //点击地图获取经纬度
      map.addEventListener("click", function(e) {
        this_.bmap.clearOverlays();
        var geocoder = new BMap.Geocoder();
        geocoder.getLocation(new BMap.Point(e.point.lng, e.point.lat), function(
          res
        ) {
          this_.store.pointX = res.point.lng;
          this_.store.pointY = res.point.lat;
          this_.bmap.centerAndZoom(res.point, 14);
          var marker = new BMap.Marker(
            new BMap.Point(res.point.lng, res.point.lat)
          );
          this_.bmap.addOverlay(marker);
          marker.setAnimation(BMAP_ANIMATION_BOUNCE);
          this_.store.address = res.address;
        });
      });
    },
    miniCode(row) {
      get("store/miniCodeUrl", { id: row.id }).then(res => {
        this.miniCodeUrl = res.data.data;
        this.$nextTick(function() {
          // DOM 更新了
          document.getElementById("miniCodeUrl_store").click();
        });
      });
    },
    recommenderDialog(row) {
      this.recommenderVisable = true;
      this.$refs.recommender.initRecommender(row.id,"store");
    },
  }
};
</script>

<style lang="less">
.pagination {
  margin: 10px 0;
  position: relative;
  display: flex;
}
</style>
